Skip to content
c++
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
constexpr int N = 2e5 + 5;
constexpr int M = 1e6 + 5;

struct edge {
    int u, v, w;
} e[N];
int head[N], to[M], nxt[M], t[M], tot;
void add(int u, int v, int w) {
    nxt[++tot] = head[u];
    head[u] = tot;
    to[tot] = v;
    t[tot] = w;
}
int dfn[N], low[N], timer;
int scc[N], scc_cnt;
int stk[N], top;

int n, m;
void tarjan(int u) {
    dfn[u] = low[u] = ++timer;
    stk[++top] = u;
    for (int i = head[u]; i; i = nxt[i]) {
        int v = to[i];
        if (!dfn[v]) {
            tarjan(v);
            low[u] = std::min(low[u], low[v]);
        } else if (!scc[v]) {
            low[u] = std::min(low[u], dfn[v]);
        }
    }
    if (low[u] == dfn[u]) {
        ++scc_cnt;
        int v;
        do {
            v = stk[top--];
            scc[v] = scc_cnt;
        } while (v != u);
    }
}
void work() {
    for (int i = 1; i <= n; i++)
        if (!dfn[i]) tarjan(i);
}

int dist[N];
using P = std::pair<int, int>;
void fc() {
    std::cin >> n >> m;
    for (int i = 0; i < m; i++) {
        std::cin >> e[i].u >> e[i].v >> e[i].w;
        add(e[i].u, e[i].v, e[i].w);
    }
    work();
    for (int i = 1; i <= scc_cnt; i++) head[i] = 0;
    tot = 0;

    for (int i = 0; i < m; i++) {
        int u = scc[e[i].u], v = scc[e[i].v];
        if (u == v) continue;
        add(u, v, e[i].w);
    }

    std::priority_queue<P, std::vector<P>, std::greater<P>> q;
    q.push({0,scc[1]});
    for(int i=1;i<=scc_cnt;i++)dist[i]=INT_MAX;
    dist[scc[1]] = 0;
    


    while (q.size()) {
        auto [d,u] = q.top();
        q.pop();
        if (dist[u] < d) continue;
        for (int i = head[u]; i; i = nxt[i]) {
            int v = to[i];
            int dw = t[i] + d;
            if (dw < dist[v]) {
                dist[v] = dw;
                q.push({dw,v});
            }
        }
    }
    std::cout<<dist[scc[n]];
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int t = 1;
    // std::cin>>t;
    while (t--) fc();
    return 0;
}